<!--
按钮-配置数据源
-->
<template>
  <div>
    <div v-if="dataSource && dataSource.name">
      已配置
      <el-button-group>
        <el-button type="" icon="el-icon-edit" @click="open"></el-button>
        <el-button type="" icon="el-icon-delete" @click="handleDelete"></el-button>
      </el-button-group>
    </div>
    <el-button v-else icon="el-icon-edit" @click="open">配置数据源</el-button>
    <edit-data-source v-if="visible"
                      :ds="ds2"
                      @close="visible=false"
                      @success="handleSuccess"></edit-data-source>
  </div>

</template>
<script>
  import vpd from '../designer/mixins/vpd';
  import EditDataSource from './index.vue';

  export default {
    mixins: [vpd],
    components: {
      EditDataSource
    },
    props: {
      ds: {
        type: Object,
        default: function () {
          return {}
        }
      }
    },
    data() {
      return {
        visible: false,
        ds2: {}
      }
    },
    computed: {
      activeElement() {
        return this.$vpd.state.activeElement
      },
      isGlobal() {
        return this.activeElement.page;
      },
      dataSource() {
        if (this.activeElement.page) {
          return this.ds2;
        }
        if (this.activeElement && this.activeElement.dataSource) {
          return this.activeElement.dataSource;
        }
        return null;
      }
    },
    created(){
      this.ds2 = this.ds || {};
    },
    methods: {
      open() {
        this.visible = true;
      },
      handleSuccess(data) {
        this.visible = false;
        Object.assign(this.ds2, data);
        this.$emit('change', data);

      },
      handleDelete() {
        if (this.isGlobal) {
          this.ds2 = {};
          this.$emit('change', {});
        } else {
          this.$vpd.commit('dataSource', {
            uuid: this.activeElement.uuid,
            dataSource: null
          })
        }

      }
    }
  }
</script>
